# -*- coding = utf-8 -*-
import pandas as pd
import numpy as np
import math

if __name__ == "__main__":
    # 输入要求解的矩阵
    matrix = pd.DataFrame(
        np.array([
            [0, 3, 2, 0, 0, 0],
            [40, 1, 1, 1, 0, 0],
            [60, 2, 1, 0, 1, 0],
            [30, 1, 0, 0, 0, 1],
        ]),
        index=['obj', '2', '3', '4'],  # 竖索引
        columns=['b', '0', '1', '2', '3', '4']  # 列索引
    )

    subscribe_set = [i for i in range(matrix.shape[1] - 1)]
    # [0, 1, 2, 3, 4]
    cj = matrix.iloc[0, 1:]
    # 按下标最小入基
    flag = []
    for i in range(5):
        if cj[i] > 0:
            flag.append(i)
    cj_submin = min(flag)

    while cj[cj_submin] > 0:
        # 按下标最小入基
        cj = matrix.iloc[0, 1:]
        # 1.选择入基变量
        flag = []
        for i in range(5):
            if cj[i] > 0:
                flag.append(i)
        cj_submin = min(flag)
        in_x_idx = matrix.columns[cj_submin + 1]  # 入基变量索引
        # 2.选择出基变量
        # 按下标最小出基
        # 计算比值
        b = matrix.iloc[1:, 0]
        in_x_value = matrix.iloc[1:][in_x_idx]
        # ----------------------------------
        ratio = b / in_x_value
        ratio_value = []
        for i in range(3):
            ratio_value.append(ratio[i])
        for i in range(3):
            if ratio_value[i] == 0:
                ratio_value[i] = 999
        print(ratio_value)
        # 找的哪一行的值最小，然后返回这个行数为idx_min
        idx_min = ratio_value.index(min(ratio_value))
        print(idx_min)
        out_x_idx = matrix.index[idx_min+1]
        # ----------------------------------
        # 3. 旋转入基出基
        pivot_element = matrix.loc[out_x_idx, in_x_idx]  # 主元
        #  出基的那一行    =   出基的那一行     /      出基的那一行入基的那一列（主元）
        matrix.loc[out_x_idx, :] = matrix.loc[out_x_idx, :] / pivot_element
        # 消元变换
        for idx in matrix.index:
            if idx != out_x_idx:
                raw_parameter = matrix.loc[idx, in_x_idx]  # 行变换系数
                matrix.loc[idx, :] = matrix.loc[idx, :] - matrix.loc[out_x_idx, :] * raw_parameter  # 做行变换
        # 替换索引
        idx = matrix.index.tolist()
        out_i = idx.index(out_x_idx)  # 先找出出基变量的索引位置
        idx[out_i] = in_x_idx  # 把入基变量放入这个位置
        # 更新矩阵索引
        matrix.index = idx
        print(matrix)

    # 打印结果
    print("目标函数值是：", - matrix.iloc[0, 0])  # 函数值存放的位置
    print("最后得到的基变量是：")
    Xi = matrix.index[1:].tolist()  # 基变量
    for xi in Xi:
        print(xi, '=', matrix.loc[xi, 'b'])
